跳到主要内容

17 电话号码的字母组合

https://leetcode.cn/leetbook/read/top-interview-questions-medium/xvpj16/

cost: 20m30s

class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.size() == 0) {
return {};
}
vector<string> res;
string combination = "";
this->walk(res, digits, 0, combination);
return res;
}

private:
void walk(vector<string>& res, string& digits, int k, string& combination) {
if (k == digits.size()) {
res.push_back(combination);
return;
}
string s = this->phoneMap[digits[k]];
for (const char ch : s) {
combination.push_back(ch);
this->walk(res, digits, k + 1, combination);
combination.pop_back();
}
}

unordered_map<char, string> phoneMap = {
{'2', "abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"},
{'6', "mno"}, {'7', "pqrs"}, {'8', "tuv"}, {'9', "wxyz"},
};
};